from django.shortcuts import render, redirect
from la import models
from la.form.form import MemberInfoModelForm


def member_info(req):
    memberinfo = models.member.objects.filter().all()
    return render( req, "member_info.html",{"memberinfo":memberinfo})


def member_add(req):
    if req.method == "GET":
        form = MemberInfoModelForm()
        return render( req, "member_add.html", { "form": form} )
    form = MemberInfoModelForm( data=req.POST )
    if form.is_valid():
        print('s')
        form.instance.points = 0
        form.save()
        return redirect( "/la/member/" )
    else:
        return render( req, "member_info.html", {"form": form} )

def member_edit(req, nid):
    """用户信息修改操作"""
    if req.method == "GET":
        memberifno = models.member.objects.filter(id=nid).all().first()
        form = MemberInfoModelForm(instance=memberifno)
        return render(req, "member_edit.html", {"form":form})
    memberifno = models.member.objects.filter(id=nid).all().first()
    form = MemberInfoModelForm(data=req.POST,instance=memberifno)
    if form.is_valid():
        points = models.member.objects.filter(id=nid).first().points
        form.instance.points = points
        form.save()
        return redirect("/la/member/")
    else:
        return render(req, "member_edit.html", {"form": form})


def member_points(req, nid):
    memberinfo = models.member.objects.filter( id=nid ).all().first()
    if req.method == "GET":
        return render(req, "member_points.html", {"memberinfo":memberinfo})
    oppoints = req.POST.get('oppoints')
    name = memberinfo.name
    phone = memberinfo.phone
    points = memberinfo.points
    models.member.objects.filter(id=nid).update(points = int(oppoints) + int(points))
    models.memberOP.objects.create(name=name,phone=phone,oppoints=oppoints)
    return redirect("/la/member/")